package com.rui.study.micro.usermanager.service.impl;

import com.rui.study.commons.model.BizException;
import com.rui.study.micro.usermanager.entity.UserInfo;
import com.rui.study.micro.usermanager.mapper.UserMapper;
import com.rui.study.micro.usermanager.service.UserService;
import com.rui.study.micro.usermanager.util.StatusCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private UserMapper userMapper;


    @Override
    public int createUserInfo(UserInfo userInfo) throws BizException {
        String username = userInfo.getUsername().toString();
        // 检查用户是否存在
        Long userId = userMapper.selectUserId(username);
        if (userId != null && userId > 0)
            throw new BizException(StatusCode.USERNAME_ALREADY_EXIST);
        // 创建用户
        int result = userMapper.insertUserInfo(userInfo);
        if (result <= 0)
            throw new BizException(StatusCode.INSERT_EXCEPTION);
        LOGGER.info("Create user [{}] succeed.", username);
        return result;
    }

    @Override
    public UserInfo loadUserInfo(String username) {
        return userMapper.selectUserInfo(username);
    }
}
